from time import sleep

from appium import webdriver
from selenium.webdriver.common.by import By
import time
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait


def connect_appium():
    desired_caps = {
        'platformName': 'Android',
        'platformVersion': '7.1.2',
        'deviceName': '192.168.5.8:5555',
        'appPackage': 'com.android.flysilkworm',
        'appActivity': '.app.activity.FrameworkActivity',
        'automationName': 'UiAutomator2',
        'noReset': True,
        'unicodeKeyboard': True,
        'resetKeyboard': True,
    }

    try:
        # 打印调试信息
        print("尝试连接 Appium，参数：", desired_caps)
        driver2 = webdriver.Remote('http://127.0.0.1:4723/wd/hub', desired_caps)
        driver2.implicitly_wait(10)
        print("✅ 成功连接到 Appium 服务器")
        return driver2

    except Exception as e:
        print(f"❌ 连接失败: {str(e)}")

        # 具体错误分析
        if "Original error" in str(e):
            print("可能原因：设备未连接/App未安装/权限问题")
        elif "Connection refused" in str(e):
            print("请检查 Appium 服务器是否启动（默认端口 4723）")
        return None


# 使用示例
if __name__ == '__main__':
    driver = connect_appium()
    if driver:
        try:
            print("Driver 已创建，可执行测试操作")
            print(driver.contexts)
            # 示例：点击某个元素
            driver.find_element(By.ID,"com.android.flysilkworm:id/tv_login_title").click()
            driver.find_element(By.ID,"com.android.flysilkworm:id/edit_phone").send_keys("111")
            driver.find_element(By.ID, "com.android.flysilkworm:id/btn_login").click()
            # 模糊匹配：contains
            toast_xpath = "//*[contains(@text, '请输入验证码')]"
            # 精准匹配
            # //*[@text='请输入验证码']
            try:
                toast = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, toast_xpath)))
                print("Toast内容:", toast.text)  # 获取Toast文本
                print("Toast可见性:", True)  # 无需用is_displayed()
            except Exception as e:
                print("Toast未找到:", str(e))

        finally:
            driver.quit()